﻿using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.HttpModules.Config;
using DesertedRoadStudios.BlogNetNuke.Components;

namespace DesertedRoadStudios.BlogNetNuke
{
    public partial class HostControl : PortalModuleBase
    {
        Panel pnlHost;
        Panel pnlNotHost;
        TextBox tbAddFriendly;
        ListBox lbPaths;
        CheckBox cbFriendly;
        HtmlControl pathsTable;
        DotNetNuke.UI.UserControls.LabelControl lblPaths;

        protected void Page_Init(object sender, EventArgs e)
        {
            pnlHost = FindControl("pnlHost") as Panel;
            pnlNotHost = FindControl("pnlNotHost") as Panel;
            tbAddFriendly = FindControl("tbAddFriendly") as TextBox;
            lbPaths = FindControl("lbPaths") as ListBox;
            cbFriendly = FindControl("cbFriendly") as CheckBox;
            pathsTable = FindControl("pathsTable") as HtmlControl;
            lblPaths = FindControl("lblPaths") as DotNetNuke.UI.UserControls.LabelControl;

            // Protect settings for host eyes only
            DotNetNuke.Entities.Users.UserInfo ui = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
            pnlHost.Visible = ui.IsSuperUser;
            pnlNotHost.Visible = !ui.IsSuperUser;
        }

        protected void btnAddFriendly_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbAddFriendly.Text))
            {
                BlogNetNukeController bnn = new BlogNetNukeController();
                string path = tbAddFriendly.Text;

                if (!path.StartsWith("/")) path = "/" + path;
                if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);

                bool found = false;

                foreach (ListItem item in lbPaths.Items)
                    if (item.Text.ToLower().Equals(path.ToLower()))
                    {
                        found = true;
                        break;
                    }

                if (!found)
                {
                    bnn.InsertFriendlyURL(path);
                    RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
                    RewriterRule rule = new RewriterRule();
                    rule.LookFor = "[^?]*" + path + "(.*)";
                    rule.SendTo = "~/BNNDefault.aspx";
                    rules.Add(rule);
                    RewriterConfiguration.SaveConfig(rules);

                    BindPaths();
                }

                tbAddFriendly.Text = string.Empty;
            }
        }

        protected void btnDeleteFriendly_Click(object sender, EventArgs e)
        {
            if (lbPaths.SelectedIndex > -1)
            {
                List<string> deletedRules = new List<string>();
                BlogNetNukeController bnn = new BlogNetNukeController();

                foreach (ListItem item in lbPaths.Items)
                    if (item.Selected)
                    {
                        bnn.DeleteFriendlyURL(Convert.ToInt32(item.Value));
                        deletedRules.Add("[^?]*" + item.Text + "(.*)");
                    }

                RewriterRuleCollection newRules = new RewriterRuleCollection();
                RewriterRuleCollection oldRules = RewriterConfiguration.GetConfig().Rules;
                RewriterRule rule;
                newRules = oldRules;

                for (int i = 0; i < oldRules.Count; i++)
                {
                    rule = oldRules[i];
                    if (deletedRules.Contains(rule.LookFor))
                        newRules.RemoveAt(i);
                }

                RewriterConfiguration.SaveConfig(newRules);

                BindPaths();
            }

            tbAddFriendly.Text = string.Empty;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindPaths();

                BlogNetNukeController bnn = new BlogNetNukeController();
                bool useFriendlier = Convert.ToBoolean(bnn.GetSetting(-1, -1, "FriendlierUrls"));

                cbFriendly.Checked = useFriendlier;
                lblPaths.Visible = useFriendlier;
                pathsTable.Visible = useFriendlier;
            }
        }

        private void BindPaths()
        {
            BlogNetNukeController bnn = new BlogNetNukeController();
            lbPaths.Items.Clear();
            lbPaths.DataSource = bnn.GetFriendlyURLs();
            lbPaths.DataValueField = "PathID";
            lbPaths.DataTextField = "Path";
            lbPaths.DataBind();
        }

        protected void cbFriendly_CheckedChanged(object sender, EventArgs e)
        {
            lblPaths.Visible = cbFriendly.Checked;
            pathsTable.Visible = cbFriendly.Checked;
            tbAddFriendly.Text = string.Empty;

            if (cbFriendly.Checked)
                EnableRules();
            else
                DisableRules();

            BlogNetNukeController bnn = new BlogNetNukeController();
            bnn.SetSetting(-1, -1, "FriendlierUrls", cbFriendly.Checked.ToString());
        }

        private void EnableRules()
        {
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
            RewriterRule rule;

            foreach (ListItem item in lbPaths.Items)
            {
                rule = new RewriterRule();
                rule.LookFor = "[^?]*" + item.Text + "/(.*)";
                rule.SendTo = "~/BNNDefault.aspx";
                rules.Add(rule);
            }

            RewriterConfiguration.SaveConfig(rules);
        }

        private void DisableRules()
        {
            List<string> deletedRules = new List<string>();

            foreach (ListItem item in lbPaths.Items)
                deletedRules.Add("[^?]*" + item.Text + "/(.*)");

            RewriterRuleCollection newRules = new RewriterRuleCollection();
            RewriterRuleCollection oldRules = RewriterConfiguration.GetConfig().Rules;
            RewriterRule rule;
            newRules = oldRules;

            for (int i = 0; i < oldRules.Count; i++)
            {
                rule = oldRules[i];
                if (deletedRules.Contains(rule.LookFor))
                    newRules.RemoveAt(i);
            }

            RewriterConfiguration.SaveConfig(newRules);
        }
    }

}
